<template>
    <div id="container" style="width: 100%; height: 100vh;"></div>
  </template>
  
  <script setup>
  import { onMounted, ref } from 'vue';

    const apiKey = ref('#{你自己的API_KEY}');
    const emit = defineEmits(['map-click', 'update-map-center']);
  
    onMounted(() => {
    const script = document.createElement('script');
    script.src = `https://webapi.amap.com/maps?v=1.4.15&key=${apiKey.value}`;
    script.onload = () => {
      initMap();
      on('update-map-center', updateMapCenter);
    };
    document.head.appendChild(script);
  });

  let map;
  function initMap() {
    map = new AMap.Map('container', {
      resizeEnable: true, 
      zoom: 11,
      center: [120.591389, 31.314338] 
    });

    map.on('click', function(e) {
        const marker = new AMap.Marker({
        position: new AMap.LngLat(e.lnglat.getLng(), e.lnglat.getLat()),
        title: '标记'
        });
        map.add(marker);
        const lng= e.lnglat.getLng();
        const lat = e.lnglat.getLat();
        emit('map-click', {lng, lat});
        setTimeout(function() {
          map.remove(marker);
        }, 10000); 
    }); 
  }

// 更新地图中心点
function updateMapCenter({ lng, lat }) {
  if (map) {
    console.log(lng, lat );
    map.setZoomAndCenter(11, [lng, lat]);
  }
}


</script>
  
<style scoped>

</style>
  